using System.Diagnostics;
using System.Globalization;
using Localization.Shared;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using Mvc.Samples.Models;

namespace Mvc.Samples.Controllers;

public class HomeController(
	IStringLocalizer<HomeController> localizer
	) : Controller
{
	public IActionResult Index()
	{
		var currentCulture = CultureInfo.CurrentCulture.Name; // 检查实际文化
		Console.WriteLine($"当前文化: {currentCulture}");
		var articles = Data.GetArticles().Select(article => new ArticleDto
		{
			Name = localizer[article.NameKey].Value,
			Description = localizer[article.DescriptionKey].Value
		}).ToList();

		return View(articles);
	}
	
	[HttpPost]
	public IActionResult SetLanguage(string culture, string returnUrl)
	{
		Response.Cookies.Append(
			CookieRequestCultureProvider.DefaultCookieName,
			CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
			new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
		);
		return LocalRedirect(returnUrl);
	}

	public IActionResult Privacy()
	{
		return View();
	}

	[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
	public IActionResult Error()
	{
		return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
	}
}
